<script setup lang="ts">
	import { onMounted, reactive, ref } from 'vue';
	import type { PaginationParam } from '@/api/model/pageParam';
	import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
	import type { commonStatus } from '@/api/model/CommonStatus';
	import { ShopManagerModel, ShopManagerModelArray, ShopManagerQueryModel } from '../../api/model/ShopManager';
	import { addShopManagerApi, deleteShopManagerApi, disableShopManagerApi, getByIdShopManagerApi, queryShopManagerListApi, updateShopManagerApi } from '../../api/requestapi/ShopManager';

	onMounted(() => {
		getShopManagerList()
	})
	// 表格加载loading
	const loading = ref(true);
	// 控制对话框
	const dialogVisble = ref(false);
	const dialogAttribute = ref({ title: "" })

	// 查询参数
	const ShopManagerQueryData = ref<ShopManagerQueryModel>({
		username: "",
		realName: "",
		lastLoginTime: "",
		status: "",
	})

	const ShopManagerData = ref<ShopManagerModelArray>([])

	// 状态查询栏的查询数据
	const status_list = ref([
		{ "value": "1", "label": "正常" },
		{ "value": "0", "label": "禁用" }
	])

	// 分页参数
	const pagination = ref<PaginationParam>({
		currentPage: 1,   //当前页码
		pageSize: 10,      //每页记录数
		total: 0         //总条数
	})

	const handleSizeChange = (pageSize : number) => {
		pagination.value.pageSize = pageSize;
		getShopManagerList()
	}

	const handleCurrentChange = (page : number) => {
		pagination.value.currentPage = page;
		getShopManagerList()
	}
	// 分页条件查询的内容框架
	const conditionList = reactive([
		{
			id: 1,
			type: "input",
			label: "店长账号",
			prop: "username",
			placeholder: "请输入查询的店长账号",
			span: 6,
		},
		{
			id: 2,
			type: "input",
			label: "店长真名",
			prop: "realName",
			placeholder: "请输入查询的店长真名",
			span: 6,
		},
		{
			id: 4,
			type: "datetime",
			label: "最后的登录时间",
			prop: "lastLoginTime",
			placeholder: "请选择最后登录的时间",
			span: 6,
		},
		{
			id: 5,
			type: "select",
			label: "状态",
			prop: "status",
			placeholder: "请选择当前店长状态",
			optionList: [
				{
					label: "正常",
					value: "1",
				},
				{
					label: "禁用",
					value: "0",
				},
			],
			span: 6,
		},
	])
	// 存放表单校验数据
	const ShopManagerRef = ref<FormInstance>()
	// 清除表单校验的红字
	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}

	// 分页条件查询
	const getShopManagerList = async () => {
		loading.value = true;
		const res = await queryShopManagerListApi(ShopManagerQueryData.value.username, ShopManagerQueryData.value.realName, ShopManagerQueryData.value.lastLoginTime, ShopManagerQueryData.value.status, pagination.value.currentPage, pagination.value.pageSize)
		console.log(res);
		if (res.code) {
			ShopManagerData.value = res.data.list
			pagination.value.total = res.data.total
		}
		loading.value = false;
	}


	// 清空按钮
	const cleanSet = () => {
		ShopManagerQueryData.value.username = ''
		ShopManagerQueryData.value.realName = ''
		ShopManagerQueryData.value.lastLoginTime = ''
		ShopManagerQueryData.value.status = ''
		getShopManagerList()
	}
	// --------------------------------------------新增用户-------------------------------------------------
	const ShopManager = ref<ShopManagerModel>({
		username: '',
		email: '',
		phone: '',
		realName: '',
		imgUrl: '',
		lastLoginTime: "",
		createdTime: '',
		updatedTime: '',
		status: ''
	})
	// 存放表单校验数据
	const userRef = ref<FormInstance>()

	//表单校验规则
	const rules = ref<FormRules>({
		username: [
			{ required: true, message: '用户名不能为空', trigger: 'blur' },
			{ min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
		],
		realName: [
			{ required: true, message: '真实姓名不能为空', trigger: 'blur' },
			{ min: 3, max: 10, message: '真实姓名长度在 3 到 10 个字符', trigger: 'blur' },
		],
		email: [
			{ required: true, message: '邮箱不能为空', trigger: 'blur' },
			{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
		],
		phone: [
			{ required: true, message: '手机号不能为空', trigger: 'blur' },
			{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
		],
		status: [
			{ required: true, message: '状态不能为空', trigger: 'change' },
		],
	})


	// 上传图片

	const handleAvatarSuccess : UploadProps['onSuccess'] = (
		response,
		uploadFile
	) => {
		console.log(response.data);
		ShopManager.value.imgUrl = response.data
	}

	const beforeAvatarUpload : UploadProps['beforeUpload'] = (rawFile) => {
		if (!rawFile) {
			ElMessage.error("请传入图片文件！")
			return false;
		}
		if (!rawFile.type.startsWith('image/')) {
			ElMessage.error('文件格式不正确!')
			return false
		} else if (rawFile.size / 1024 / 1024 > 2) {
			ElMessage.error('文件大小不能超过2MB')
			return false
		}
		return true
	}

	// 关闭对话框事件
	const handleClose = () => {
		ShopManager.value = {
			username: '',
			email: '',
			phone: '',
			realName: '',
			imgUrl: '',
			lastLoginTime: "",
			createdTime: '',
			updatedTime: '',
			status: ''
		}
		// console.log('对话框已关闭');
	};
	const dialogRef = ref()

	// 确认事件
	const handleSuccess = async (formEl : FormInstance | undefined) => {
		const isValid = await dialogRef.value?.validate(userRef.value)
		if (!isValid) return
		let res = null
		if (ShopManager.value.id) {
			// id 有值代表修改，
			res = await updateShopManagerApi(ShopManager.value)
		} else {
			// id没值代表新增
			res = await addShopManagerApi(ShopManager.value)
		}
		if (res.code) {
			ElMessage.success('操作成功')
			dialogVisble.value = false;
			getShopManagerList()
		} else {
			ElMessage.error(res.msg)
		}
	};
	const addShopManager = () => {
		resetForm(ShopManagerRef.value)
		dialogVisble.value = true;
		dialogAttribute.value.title = '新增站长'
	}

	// -----------------------------编辑用户信息-----------------------------------
	// 编辑用户回显
	const updateShopManager = async (id : number) => {
		resetForm(ShopManagerRef.value)
		console.log("当前用户id:" + id);
		dialogVisble.value = true;
		dialogAttribute.value.title = '修改站长'
		const res = await getByIdShopManagerApi(id);
		if (res.code) {
			ShopManager.value = res.data
		}
	}

	// -----------------------------(批量)删除管理员信息-----------------------------------
	// 批量删除的ids
	const selectedIds = ref<(number | undefined)[]>([]);

	// 多选框多选
	const handleSelectionChange = (val : ShopManagerModel[]) => {
		selectedIds.value = val.map(element => { return element.id })
	}

	const deleteShopManager = async (id : string) => {
		console.log("当前要删除的用户id：" + id);
		const res = await deleteShopManagerApi(id);
		if (res.code) {
			ElMessage.success("删除成功");
			getShopManagerList()
		} else {
			ElMessage.error("删除失败");
		}
	}

	const deleteBatchShopManager = async () => {
		console.log("当前要删除的用户id：" + selectedIds.value);
		const res = await deleteShopManagerApi(selectedIds.value.toString())
		if (res.code) {
			ElMessage.success("删除成功");
			getShopManagerList()
		} else {
			ElMessage.error("删除失败");
		}
	}


	// -----------------------------禁用(启用)管理员-----------------------------------
	// 状态
	const adminStatus = ref<commonStatus>({
		id: 0,
		status: ''
	})
	const disableUser = async (row : any) => {
		adminStatus.value.id = row.id;
		adminStatus.value.status = row.status
		// console.log("当前要禁用的用户：" + row.status);
		// console.log("当前要禁用的用户：" + row.id);
		console.log("当前要禁用的用户：" + adminStatus.value);
		const res = await disableShopManagerApi(adminStatus.value);
		if (res.code) {
			if (row.status == "1") { ElMessage.warning("禁用成功，账号已被禁用！！"); getShopManagerList() }
			else {
				ElMessage.success("启用成功，账号可以正常使用！！");
				getShopManagerList()
			}
		} else {
			ElMessage.error("禁用失败");
		}
	}
</script>

<template>
	<h1>熊吃外卖平台管理员账号管理</h1>
	<div style="width: 95%;">
		<div>
			<ConditionBar v-model:searchParams="ShopManagerQueryData" @search="getShopManagerList" @reset="cleanSet"
				:conditionList="conditionList" />
		</div>
		<Dialog v-model:dialogVisble="dialogVisble" v-model:dialogTitle="dialogAttribute.title" @close="handleClose"
			@success="handleSuccess" ref="dialogRef">
			<el-form :model="ShopManager" :rules="rules" ref="userRef" label-width="100px">
				<!-- 用户名 -->
				<el-form-item label="用户名" prop="username">
					<el-input v-model="ShopManager.username" placeholder="请输入用户名" />
				</el-form-item>
				<el-form-item label="真实姓名" prop="realName">
					<el-input v-model="ShopManager.realName" placeholder="请输入真实姓名" />
				</el-form-item>

				<!-- 邮箱 -->
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="ShopManager.email" placeholder="请输入邮箱" />
				</el-form-item>

				<!-- 手机号 -->
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="ShopManager.phone" placeholder="请输入手机号" />
				</el-form-item>

				<!-- 上传头像 -->
				<el-form-item v-if="dialogAttribute.title == '新增店长'" label="上传头像" prop="imgUrl">
					<el-upload class="avatar-uploader" action="/api/admin/common/upload" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						<img v-if="ShopManager.imgUrl" :src="ShopManager.imgUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>

				<!-- 状态 -->
				<el-form-item label="状态" prop="status">
					<el-select v-model="ShopManager.status" placeholder="请选择状态">
						<el-option label="正常" :value="1" />
						<el-option label="禁用" :value="0" />
					</el-select>
				</el-form-item>
			</el-form>
		</Dialog>
		<div style="margin: 20px 0px 20px 0px;">
			<el-button type="success" @click="addShopManager">新增店长</el-button>
			<el-button type="danger" @click="deleteBatchShopManager">批量删除</el-button>
		</div>
		<div>
			<el-table :data="ShopManagerData" border style="width: 100%" height="500px" empty-text="当前没有数据"
				v-loading="loading" @selection-change="handleSelectionChange" element-loading-text="数据加载中...">
				<el-table-column type="selection" width="55" />
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="username" label="账号" width="80" />
				<el-table-column prop="realName" label="注册人姓名" width="100" />
				<el-table-column prop="email" label="注册邮箱" width="160" />
				<el-table-column prop="phone" label="手机号" width="120" />
				<el-table-column prop="imgUrl" label="头像" width="135">
					<template #default="scope">
						<el-image :src="scope.row.imgUrl" style="width: 100px; height: 100px" />
					</template>
				</el-table-column>
				<el-table-column prop="shopName" label="所拥有店铺名称" width="120" />
				<el-table-column prop="lastLoginTime" label="上次登录时间" width="145" />
				<el-table-column prop="createdTime" label="创建时间" width="145" />
				<el-table-column prop="updatedTime" label="更新时间" width="145" />
				<el-table-column prop="status" label="账号状态" width="90">
					<template #default="scope">
						<span v-if="scope.row.status=='1'">
							<el-tag type="success">正常</el-tag>
						</span>
						<span v-else>
							<el-tag type="danger">禁用</el-tag>
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="operatorName" label="操作人名字" width="80" />
				<el-table-column label="操作" width="230" fixed="right">
					<template #default="scope">
						<el-button type="primary" @click="updateShopManager(scope.row.id)">编辑</el-button>
						<el-button type="danger" @click="deleteShopManager(scope.row.id)">删除</el-button>
						<el-button v-if="scope.row.status=='1'" type="warning"
							@click="disableUser(scope.row)">禁用</el-button>
						<el-button v-else type="success" @click="disableUser(scope.row)">启用</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<div style="margin-top: 20px;">
			<el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
				:page-sizes="[10,20,30,40]" background="true" layout="total, sizes, prev, pager, next, jumper"
				:total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>